package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"rpc/model/mysql"
	"rpc/pkg"

	"rpc/internal/svc"
	"rpc/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrderLogic {
	return &AddOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddOrderLogic) AddOrder(in *order.AddOrderRequest) (*order.AddOrderResponse, error) {
	// todo: add your logic here and delete this line
	var goods mysql.OrderGoods
	mysql.DB.Where("id=?", in.GoodsId).Limit(1).Find(&goods)
	if goods.ID == 0 {
		return nil, fmt.Errorf("该商品不存在")
	}
	var user mysql.User
	mysql.DB.Where("id=?", in.UserId).Limit(1).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该账号不存在")
	}
	if user.Checked != 1 {
		return nil, fmt.Errorf("该用户状态不正确")
	}
	s := uuid.NewString()
	amount := float64(goods.GoodsNum) * goods.GoodsPrice
	m := mysql.Order{
		UserId:     int(in.UserId),
		GoodsId:    int(in.GoodsId),
		OrderSn:    s,
		GoodsName:  goods.GoodsName,
		GoodsCover: goods.GoodsCover,
		Amount:     amount,
		PayType:    1,
	}
	mysql.DB.Create(&m)
	sprintf := fmt.Sprintf("%.2f", m.Amount)
	url := pkg.AliPay(m.GoodsName, s, sprintf)
	return &order.AddOrderResponse{Url: url}, nil
}
